/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.max.oti.system.bean.sppp;

import com.max.oti.system.model.AdviserPractice;
import com.max.oti.system.model.HistoryPractice;
import com.max.oti.system.model.Jury;
import com.max.oti.system.model.Practice;
import com.max.oti.system.model.ReportPractice;
import com.max.oti.system.model.State;
import com.max.oti.system.model.SupervisionPractice;
import com.max.oti.system.model.SustentationPractice;
import com.max.oti.system.model.TypeComission;
import com.max.oti.system.service.interfac.IAdviserPracticeService;
import com.max.oti.system.service.interfac.IHistoryPracticeService;
import com.max.oti.system.service.interfac.IPracticeService;
import com.max.oti.system.service.interfac.IReportPracticeService;
import com.max.oti.system.service.interfac.ISupervisionPracticeService;
import com.max.oti.system.service.interfac.ISustentationPracticeService;
import com.max.oti.system.util.Clazz;
import com.max.oti.system.util.FacesUtil;
import com.max.oti.system.util.file.PATH_DEFAULT;
import com.sf.tm.max.file.MFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author max
 */
@ManagedBean
@SessionScoped
public class PracticeProcessBean implements Serializable {

    @ManagedProperty("#{clazz}")
    Clazz clazz;
    @ManagedProperty("#{historyPracticeService}")
    IHistoryPracticeService historyPracticeService;
    @ManagedProperty("#{adviserPracticeService}")
    IAdviserPracticeService adviserPracticeService;
    @ManagedProperty("#{practiceService}")
    IPracticeService practiceService;
    @ManagedProperty("#{supervisionPracticeService}")
    ISupervisionPracticeService supervisionPracticeService;
    @ManagedProperty("#{reportPracticeService}")
    IReportPracticeService reportPracticeService;
    @ManagedProperty("#{sustentationPracticeService}")
    ISustentationPracticeService sustentationPracticeService;
    ////////////////////////////////////////////////////////////
    private Practice practice;
    private AdviserPractice adviserPractice = new AdviserPractice();
    private String subNameTeacher;
    ///////////////////////////////////////////////////////////////
    private boolean asesor;
    private boolean supervisar;
    private boolean entregaInforme;
    private boolean asignarJurado;
    private boolean calificar;
    private boolean validarCorreciones;
    private boolean anularPracticaSupervision;
    private boolean archivo;
    private boolean segundaCalificacion;
    ///////////////////////////////////////////////////////////////
    private boolean globalUpdate;
    private boolean globalUpdateRegister;
    ///////////////////////////////////////////////////////////////
    private String nombreDecano = "MSC. WALTER BERNUY BLANCO";
    //////////////////////////////////////////////////////////////
    private String navigation = "./process_content/home.xhtml";
    //////////////////////////////////////////////////////////////
    private SupervisionPractice supervisionPractice;
    private String anuladoPoSupervisionDetalle;
    //////////////PARA REGISTRO DE INFORME////////////////
    private ReportPractice reportPractice;
    ////////////PARA LA ASIGNACIÓN DE JURADOS//////////////
    private String presidente;
    private String secretario;
    private String vocal1;
    private String vocal2;
    private Date diaSustentacion;
    private String lugarSustentacion;
    private String documentoFormal;
    private Date diaEmision;
    private List<String> listTeacher;
    private String subOne;
    private String subTwo;
    private String subTree;
    private String subFour;
    ////////////PARA LA CALIFICACION DEL PRACTICANTE DESPUES DE LA SUSTENTACION////////////
    private Integer notaFinal;
    private List<String> condicion;
    private String detalle;
    private String stateSelected;
    ///////////////GUARDAR EL REPORT PRACTICE/////////////////
    private ReportPractice reportPracticeFinal;

    public void initCollection() {
        System.out.println("Entro al constructor");
        globalUpdateRegister = false;
        adviserPractice = new AdviserPractice();
        supervisionPractice = new SupervisionPractice();
        reportPractice = new ReportPractice();
        navigation = "./process_content/home.xhtml";


        filter();
    }

    //METODO IMPORTANTE
    public void filter() {
        if (dentroDeLaFechaDePracticas()) {
            if (anuladoPorSupervision()) {
                ////////////////////////////////////////////////////////////////////////////////
                FacesUtil.addMessage("Anulado por supervisión", null, FacesMessage.SEVERITY_WARN);
                System.out.println("Anulado por supervisión");
                globalUpdate = false;
                ////////////////////////////////////////////////////////////////////////////////
            } else {
                if (aprovadoTotal()) {
                    if(practicaCulminada()) {
                        globalUpdate = false;
                    } else {
                        advanzeShow();
                    }
                    
                    //globalUpdate = false;
                } else {
                    if (desaprovadaPractica()) {
                        globalUpdate = false;
                    } else {
                        //ACA VER EN QUE ESTADO ESTA
                        advanzeShow();
                    }

                }

            }
        } else {
            if (anuladoPorSupervision()) {
                ////////////////////////////////////////////////////////////////////////////////
                FacesUtil.addMessage("Anulado por supervisión", null, FacesMessage.SEVERITY_WARN);
                globalUpdate = false;
                //              ParamSend.setShowStatePractice(false);
                ////////////////////////////////////////////////////////////////////////////////
            } else {
                System.out.println("No se encuentra anulado, por lo que se debe Registrar como anulado por que vencio la fecha");
                try {
                    //BUSCARA SI ES QUE AUN TIENE CHANCE DE SUSTENTAR A PESAR DE QUE DESAPROVO CON CORRECCIONES
                    HistoryPractice hp = regresarSustentacion();
                    if (hp != null) {
                        Date dt = hp.getDate();
                        dt.setMonth(dt.getMonth() + 1);
                        if (dt.before(new Date())) {
                            //DESAPRUEBA
                            updateOldHistory();
                            HistoryPractice hpTemp = new HistoryPractice();
                            hpTemp.setDate(new Date());
                            hpTemp.setDetail("Desaprobado por haber excedido de la fecha de sustentación por desaprovación con correción");
                            hpTemp.setDocumentFormal("***");
                            hpTemp.setIdPractice(practice);
                            hpTemp.setIdState(clazz.STATE(Clazz.STATE.Name.DESAPROVADO, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                            hpTemp.setOldHistory(false);
                            historyPracticeService.save(hpTemp);
                            practice.getHistoryPracticeList().add(hpTemp);
                            practice.setIdHistoryPractice(hpTemp);
                            globalUpdate = false;
                        }
                    } else {
                        globalUpdate = false;
                        updateInsertHistory();
                        FacesUtil.addMessage("Anulado por entrega fuera de fecha", null, FacesMessage.SEVERITY_WARN);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Evento para guardar el archivo
     *
     * @param event
     */
    public void handleFileUpload(FileUploadEvent event) throws Exception {
        String path = FacesContext.getCurrentInstance().getExternalContext()
                .getRealPath("/");
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
        String name = fmt.format(new Date())
                + event.getFile().getFileName().substring(
                event.getFile().getFileName().lastIndexOf('.'));
        File file = new File(path + "resources/files/" + name);

        InputStream is = event.getFile().getInputstream();
        OutputStream out = new FileOutputStream(file);
        byte buf[] = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

        is.close();
        out.close();
        reportPracticeFinal.setFileUrl(name);
        FacesUtil.addMessage("Archivo Subido", null, FacesMessage.SEVERITY_INFO);
    }

    /**
     * ESTO SI HACE CLICK EN ASIGNAR ASESOR RENDERIZA EL CONTENIDO
     */
    public void changeAsesor() {
        navigation = "./process_content/adviser_practice.xhtml";
        globalUpdate = false;
        globalUpdateRegister = true;
        listTeacher = new ArrayList<String>();
        listTeacher.add("Docente 1");
        listTeacher.add("Docente 2");
        listTeacher.add("Docente 3");
        listTeacher.add("Docente 4");
        listTeacher.add("Docente 5");
    }

    public void changeSupervision() {
        navigation = "./process_content/supervision_practice.xhtml";
        globalUpdate = false;
        globalUpdateRegister = true;
    }

    public void entregaInformeRender() {
        navigation = "./process_content/give_inform.xhtml";
        globalUpdate = false;
        globalUpdateRegister = true;
    }

    public void asignacionJurado() {
        navigation = "./process_content/assignament_jury.xhtml";
        globalUpdate = false;
        globalUpdateRegister = true;

        //VARIALBES DE JURADO
        presidente = null;
        secretario = null;
        vocal1 = null;
        vocal2 = null;
        diaSustentacion = null;
        lugarSustentacion = null;
        documentoFormal = null;
        diaEmision = null;
        
        //LLAMAR Y REEMPLAZAR TRAER LOS DOCENTES DEL WEB SERVICE
        listTeacher = new ArrayList<String>();
        listTeacher.add("Docente 1");
        listTeacher.add("Docente 2");
        listTeacher.add("Docente 3");
        listTeacher.add("Docente 4");
        listTeacher.add("Docente 5");
    }

    public void calificationFinal() {
        navigation = "./process_content/calificate_first.xhtml";
        globalUpdate = false;
        globalUpdateRegister = true;
    }

    public void subirArchivoPractica() {
        reportPracticeFinal = new ReportPractice();
        navigation = "./process_content/final_practice.xhtml";
        globalUpdate = false;
        globalUpdateRegister = true;
    }
    
    public void segundaCalificacionMeth() {
        
    }
    
    private void updateOldHistory() throws Exception {
        historyPracticeService.HQLexecute("update HistoryPractice c set "
                + "c.oldHistory='true' where oldHistory='false' and c.idPractice.id=" + practice.getId());
    }
    //METODO QUE SIRVE AL METODO IMPORTANTE

    private void updateInsertHistory() throws Exception {
        boolean executeHQL = true;

        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            System.out.println(practice.getHistoryPracticeList().get(i).getIdState().getName());

            if (practice.getHistoryPracticeList().get(i)
                    .getIdState().getName()
                    .equals(Clazz.STATE.Name.ANULACION_POR_ENTREGA_DE_INFORME_FUERA_DE_FECHA)) {
                executeHQL = false;
                break;
            }
            System.out.println(executeHQL);
        }
        if (executeHQL) {
            historyPracticeService.HQLexecute("update HistoryPractice c set "
                    + "c.oldHistory='true' where oldHistory='false' and c.idPractice.id=" + practice.getId());

            HistoryPractice hp = new HistoryPractice();
            hp.setDate(practice.getEndDate());
            hp.setDetail("ANULACION_POR_ENTREGA_DE_INFORME_FUERA_DE_FECHA");
            hp.setDocumentFormal("***");
            hp.setIdPractice(practice);
            hp.setIdState(clazz.STATE(Clazz.STATE.Name.ANULACION_POR_ENTREGA_DE_INFORME_FUERA_DE_FECHA,
                    Clazz.STATE.Entity.HISOTRY_PRACTICE));
            hp.setOldHistory(false);

            System.out.println("control:" + historyPracticeService.save(hp));
            practice.getHistoryPracticeList().add(hp);
            practice.setIdHistoryPractice(hp);
        }
    }

    private HistoryPractice regresarSustentacion() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (practice.getHistoryPracticeList().get(i).getIdState().getName()
                    .equals(Clazz.STATE.Name.DESAPROVADO_CON_CORRECION)) {
                return practice.getHistoryPracticeList().get(i);
            }
        }
        return null;
    }

    private void advanzeShow() {
        if (practice.getIdAdviserPractice() == null) {
            asesor = true;
            segundaCalificacion = archivo = supervisar = entregaInforme = asignarJurado = calificar = anularPracticaSupervision = false;
        } else {
            //SI ES QUE YA EXISTE SU ASESOR ENTONCES COMIENZA EL JUEGO
            //PRIMERO OBTENEMOS EL HISTORY ACTUAL.
            State actualiS = getStateActuality();
            if (actualiS.getName().equals(Clazz.STATE.Name.ASIGNACION_DE_ASESOR_Y_RESOLUCION)) {
                //SUPERVISION//ENTREGA DE INFORME
                supervisar = entregaInforme = true;
                segundaCalificacion = archivo = asesor = asignarJurado = calificar = anularPracticaSupervision = validarCorreciones = false;
            } else if (actualiS.getName().equals(Clazz.STATE.Name.SUPERVISION)) {
                //ANULADO POR SUPERVISON//ENTREGA DE INFORME
                anularPracticaSupervision = entregaInforme = true;
                segundaCalificacion = archivo = asesor = asignarJurado = supervisar = calificar = validarCorreciones = false;
            } else if (actualiS.getName().equals(Clazz.STATE.Name.ENTREGA_DE_INFORME)) {
                //ASIGNACION DE JURADOS
                asignarJurado = true;
                segundaCalificacion = archivo = asesor = entregaInforme = validarCorreciones = anularPracticaSupervision = supervisar = calificar = false;

            } else if (actualiS.getName().equals(Clazz.STATE.Name.PARA_SUSTENTAR)) {
                //CALIFICAR.
                calificar = true;
                segundaCalificacion = archivo = asesor = entregaInforme = validarCorreciones = anularPracticaSupervision = supervisar = asignarJurado = false;
            } else if (actualiS.getName().equals(Clazz.STATE.Name.APROVADO)) {
                archivo = true;
                segundaCalificacion = validarCorreciones = calificar = asesor = entregaInforme = anularPracticaSupervision = supervisar = asignarJurado = false;
                
            } else if(actualiS.getName().equals(Clazz.STATE.Name.DESAPROVADO_CON_CORRECION)) {
                segundaCalificacion = true;
                archivo = validarCorreciones = calificar = asesor = entregaInforme = anularPracticaSupervision = supervisar = asignarJurado = false;
                
            }
        }
    }

    private State getStateActuality() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (!practice.getHistoryPracticeList().get(i).getOldHistory()) {
                return practice.getHistoryPracticeList().get(i).getIdState();
            }
        }
        return new State();
    }
    
    /**
     * GUARDA EL ASESOR
     */
    public void saveAdviserPractice() {
        System.out.println("Guardado Adviser");

        try {

            if (adviserPractice.getDateAssignment().after(practice.getStartDate())
                    && adviserPractice.getDateAssignment().before(practice.getEndDate())
                    && adviserPractice.getNameAdviser() != null 
                    && !adviserPractice.getNameAdviser().isEmpty()) {
                
                adviserPractice.setPracticeList(null);
                adviserPractice.setNameDoyen(nombreDecano);
                adviserPractice.setNameAdviser(subNameTeacher + " " + adviserPractice.getNameAdviser());
                
                int idAdviser = adviserPracticeService.save(adviserPractice);

                practiceService.HQLexecute("update Practice c set c.idAdviserPractice=" + idAdviser + " where c.id=" + practice.getId());
                updateOldHistory();
                HistoryPractice hp = new HistoryPractice();
                hp.setDate(adviserPractice.getDateAssignment());
                hp.setDetail("Se le fue asignado un asesor");
                hp.setDocumentFormal(adviserPractice.getDocumentFormal());
                hp.setIdPractice(practice);
                hp.setIdState(clazz.STATE(Clazz.STATE.Name.ASIGNACION_DE_ASESOR_Y_RESOLUCION, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                hp.setOldHistory(false);

                historyPracticeService.save(hp);
                FacesUtil.addMessage("Guardado con Exito", null, FacesMessage.SEVERITY_INFO);
            } else {
                FacesUtil.addMessage("Fuera de Fecha ó Docente no encontrado", null, FacesMessage.SEVERITY_WARN);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveReportPracticeFinal() {
        if (reportPracticeFinal.getFileUrl() == null || reportPracticeFinal.getFileUrl().isEmpty()) {
            FacesUtil.addMessage("Debe subir el PDF antes de guardar", null, FacesMessage.SEVERITY_ERROR);
            FacesUtil.addMessage("No se guardaron los cambios.", null, FacesMessage.SEVERITY_ERROR);
        } else {
            try {
                reportPracticeFinal.setIdPractice(practice);
                reportPracticeFinal.setIdState(clazz.STATE(Clazz.STATE.Name.INFORME_FINAL_ETREGADO, Clazz.STATE.Entity.REPORT_PRACTICE));

                reportPracticeService.save(reportPracticeFinal);
                updateOldHistory();

                HistoryPractice hp = new HistoryPractice();
                hp.setDate(reportPracticeFinal.getFilingDate());
                hp.setDetail(reportPracticeFinal.getDetail());
                hp.setDocumentFormal("***");
                hp.setIdPractice(practice);
                hp.setIdState(clazz.STATE(Clazz.STATE.Name.PRACTICA_CULMINADA, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                hp.setOldHistory(false);

                historyPracticeService.save(hp);
                FacesUtil.addMessage("Guardado", null, FacesMessage.SEVERITY_INFO);
            } catch (Exception ex) {
                Logger.getLogger(PracticeProcessBean.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }

    }

    /**
     * GUARDA LA SUPERVISION
     */
    public void saveSupervisionPractice() {
        try {
            if (supervisionPractice.getDate().after(practice.getStartDate())
                    && supervisionPractice.getDate().before(practice.getEndDate())) {
                supervisionPractice.setIdPractice(practice);
                supervisionPracticeService.save(supervisionPractice);

                updateOldHistory();

                HistoryPractice hp = new HistoryPractice();
                hp.setDate(supervisionPractice.getDate());
                hp.setDetail(supervisionPractice.getDetail());
                hp.setDocumentFormal(supervisionPractice.getDocumentFormal());
                hp.setIdPractice(practice);
                hp.setIdState(clazz.STATE(Clazz.STATE.Name.SUPERVISION, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                hp.setOldHistory(false);

                historyPracticeService.save(hp);
                FacesUtil.addMessage("Supervision Guardado con exito", null, FacesMessage.SEVERITY_INFO);
            } else {
                FacesUtil.addMessage("Fecha fuera de practicas...", null, FacesMessage.SEVERITY_WARN);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * GUARDA EL ESTADO DE LA SUPERVISION ANULADA
     */
    public void saveSupervisionFail() {
        try {
            updateOldHistory();

            HistoryPractice hp = new HistoryPractice();
            hp.setDate(new Date());
            hp.setDetail(anuladoPoSupervisionDetalle);
            hp.setDocumentFormal("**");
            hp.setIdPractice(practice);
            hp.setIdState(clazz.STATE(Clazz.STATE.Name.ANULACION_POR_SUPERVICION, Clazz.STATE.Entity.HISOTRY_PRACTICE));
            hp.setOldHistory(false);

            historyPracticeService.save(hp);
            FacesUtil.addMessage("PRACTICA ANULADA POR SUPERVISIÓN", null, FacesMessage.SEVERITY_INFO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * GUARDA EL ESTADO PARA LA ENTREGA DE INFORME
     */
    public void saveEntregaInforme() {
        try {
            System.out.println("Date: " + practice.getEndDate());
            Date DateFinaly = new Date();
            DateFinaly.setDate(practice.getEndDate().getDate());
            DateFinaly.setMonth(practice.getEndDate().getMonth());
            DateFinaly.setYear(practice.getEndDate().getYear());
            
            DateFinaly.setMonth(DateFinaly.getMonth() + 1);
            System.out.println("Date: " + practice.getEndDate());
            if (reportPractice.getFilingDate().after(practice.getEndDate()) && reportPractice.getFilingDate()
                    .before(DateFinaly)) {
                updateOldHistory();

                HistoryPractice hp = new HistoryPractice();
                hp.setDate(reportPractice.getFilingDate());
                hp.setDetail(reportPractice.getDetail());
                hp.setDocumentFormal("***");
                hp.setIdPractice(practice);
                hp.setIdState(clazz.STATE(Clazz.STATE.Name.ENTREGA_DE_INFORME, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                hp.setOldHistory(false);

                historyPracticeService.save(hp);

                reportPractice.setFileUrl("***");
                reportPractice.setIdPractice(practice);
                reportPractice.setIdState(clazz.STATE(Clazz.STATE.Name.ENTREGA_DE_INFORME, Clazz.STATE.Entity.REPORT_PRACTICE));

                reportPracticeService.save(reportPractice);

                FacesUtil.addMessage("Se Entrego informe con éxito", null, FacesMessage.SEVERITY_INFO);
            } else {
                FacesUtil.addMessage("Entrega de informe fuera de fecha...", null, FacesMessage.SEVERITY_WARN);
            }

        } catch (Exception ex) {
            Logger.getLogger(PracticeProcessBean.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    /**
     * GUARDA Y ASIGNA JURADOS AL PRACTICANTTE
     */
    public void saveAssignamentJury() {

        try {
            if (!diaSustentacion.before(practice.getEndDate())) {
                SustentationPractice sustentationPrac = new SustentationPractice();
                sustentationPrac.setDateSustentation(diaSustentacion);
                sustentationPrac.setIdPractice(practice);
                //sustentationPrac.setNoteFinal(20); NO SE AGREGA POR QUE TODAVIA ESTA PARA SUSTENTAR
                sustentationPrac.setPlace(lugarSustentacion);
                TypeComission tc = clazz.TYPE_COMISSION(Clazz._TYPECOMISSION.SPPP);
                
                presidente = subOne + " " + presidente;
                secretario = subTwo + " " + secretario;
                vocal1 = subTree + " " + vocal1;
                vocal2 = subFour + " " + vocal2;
                
                sustentationPrac.setJuryList(new ArrayList<Jury>());
                sustentationPrac.getJuryList().add(new Jury(presidente, "PRESIDENTE", diaEmision, tc, sustentationPrac));
                sustentationPrac.getJuryList().add(new Jury(secretario, "SECRETARIO", diaEmision, tc, sustentationPrac));
                sustentationPrac.getJuryList().add(new Jury(vocal1, "PRIMER VOCAL", diaEmision, tc, sustentationPrac));
                sustentationPrac.getJuryList().add(new Jury(vocal2, "SEGUNDO VOCAL", diaEmision, tc, sustentationPrac));

                sustentationPracticeService.save(sustentationPrac);

                updateOldHistory();

                HistoryPractice hp = new HistoryPractice();
                hp.setDate(diaSustentacion);
                hp.setDetail("El alumno se encuentra ya asignado con sus asesores y listo para Sustentar.");
                hp.setDocumentFormal(documentoFormal);
                hp.setIdPractice(practice);
                hp.setIdState(clazz.STATE(Clazz.STATE.Name.PARA_SUSTENTAR, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                hp.setOldHistory(false);

                historyPracticeService.save(hp);

                FacesUtil.addMessage("Guardado sus jurados y la fecha de sustentación", null, FacesMessage.SEVERITY_INFO);

            } else {
                FacesUtil.addMessage("La fecha debe ser mayor que la fecha final de sus practicas.", null, FacesMessage.SEVERITY_WARN);
            }
        } catch (Exception ex) {
            FacesUtil.addMessage("Prueba con exito", null, FacesMessage.SEVERITY_FATAL);
            Logger.getLogger(PracticeProcessBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    
    
    public void saveCalification() {
        FacesUtil.addMessage("Guardado", null, FacesMessage.SEVERITY_INFO);
        if (!practice.getSustentationPracticeList().isEmpty()) {
            try {
                SustentationPractice su = practice.getSustentationPracticeList().get(
                        practice.getSustentationPracticeList().size() - 1);
                sustentationPracticeService.HQLexecute("update SustentationPractice "
                        + "c set c.noteFinal=" + notaFinal + " where c.id=" + su.getId());

                updateOldHistory();

                HistoryPractice hp = new HistoryPractice();
                hp.setDate(new Date());
                hp.setDetail(detalle);
                hp.setDocumentFormal("***");
                hp.setIdPractice(practice);
                hp.setIdState(clazz.STATE(stateSelected, Clazz.STATE.Entity.HISOTRY_PRACTICE));
                hp.setOldHistory(false);

                historyPracticeService.save(hp);

            } catch (Exception ex) {
                Logger.getLogger(PracticeProcessBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Se encuentra dentro de la fecha.
     *
     * @return S
     */
    private boolean dentroDeLaFechaDePracticas() {
        Date dateTemp = practice.getEndDate();
        dateTemp.setMonth(dateTemp.getMonth() + 1);
        if (dateTemp.after(new Date())) {
            dateTemp.setMonth(dateTemp.getMonth() - 1);
            return true;
        } else {
            dateTemp.setMonth(dateTemp.getMonth() - 1);
            return false;
        }
    }

    /**
     * APROVADO SIN MAS
     */
    public boolean aprovadoTotal() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (practice.getHistoryPracticeList().get(i)
                    .getIdState().getName()
                    .equals(Clazz.STATE.Name.APROVADO)) {
                return true;
            }
        }
        return false;
    }

    /**
     * APROVADO SIN MAS
     */
    public boolean practicaCulminada() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (practice.getHistoryPracticeList().get(i)
                    .getIdState().getName()
                    .equals(Clazz.STATE.Name.PRACTICA_CULMINADA)) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * Anulado por entrega de informe fuera de fecha...
     *
     * @return
     */
    private boolean anuladoPorFueraFecha() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (practice.getHistoryPracticeList().get(i)
                    .getIdState().getName()
                    .equals(Clazz.STATE.Name.ANULACION_POR_ENTREGA_DE_INFORME_FUERA_DE_FECHA)) {
                return true;
            }
        }
        return false;
    }

    private boolean anuladoPorSupervision() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (practice.getHistoryPracticeList().get(i)
                    .getIdState().getName()
                    .equals(Clazz.STATE.Name.ANULACION_POR_SUPERVICION)) {
                return true;
            }
        }
        return false;
    }

    private boolean desaprovadaPractica() {
        for (int i = 0; i < practice.getHistoryPracticeList().size(); i++) {
            if (practice.getHistoryPracticeList().get(i)
                    .getIdState().getName()
                    .equals(Clazz.STATE.Name.DESAPROVADO)) {
                return true;
            }
        }
        return false;
    }
//<editor-fold defaultstate="collapsed" desc="Getter and Setter">


    public Practice getPractice() {
        return practice;
    }

    public List<String> getListTeacher() {
        return listTeacher;
    }

    public void setListTeacher(List<String> listTeacher) {
        this.listTeacher = listTeacher;
    }

    public void setPractice(Practice practice) {
        this.practice = practice;
    }

    public boolean isAsesor() {
        return asesor;
    }

    public boolean isSupervisar() {
        return supervisar;
    }

    public SupervisionPractice getSupervisionPractice() {
        return supervisionPractice;
    }

    public void setSupervisionPractice(SupervisionPractice supervisionPractice) {
        this.supervisionPractice = supervisionPractice;
    }

    public void setReportPracticeService(IReportPracticeService reportPracticeService) {
        this.reportPracticeService = reportPracticeService;
    }

    public String getNavigation() {
        return navigation;
    }

    public String getDetalle() {
        return detalle;
    }

    public void setDetalle(String detalle) {
        this.detalle = detalle;
    }

    public void setNavigation(String navigation) {
        this.navigation = navigation;
    }

    public boolean isAnularPracticaSupervision() {
        return anularPracticaSupervision;
    }

    public boolean isEntregaInforme() {
        return entregaInforme;
    }

    public boolean isAsignarJurado() {
        return asignarJurado;
    }

    public void setSupervisionPracticeService(ISupervisionPracticeService supervisionPracticeService) {
        this.supervisionPracticeService = supervisionPracticeService;
    }

    public boolean isCalificar() {
        return calificar;
    }

    public boolean isValidarCorreciones() {
        return validarCorreciones;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public boolean isGlobalUpdate() {
        return globalUpdate;
    }

    public void setGlobalUpdate(boolean globalUpdate) {
        this.globalUpdate = globalUpdate;
    }

    public void setHistoryPracticeService(IHistoryPracticeService historyPracticeService) {
        this.historyPracticeService = historyPracticeService;
    }

    public AdviserPractice getAdviserPractice() {
        return adviserPractice;
    }

    public String getPresidente() {
        return presidente;
    }

    public void setPresidente(String presidente) {
        this.presidente = presidente;
    }

    public Date getDiaSustentacion() {
        return diaSustentacion;
    }

    public void setDiaSustentacion(Date diaSustentacion) {
        this.diaSustentacion = diaSustentacion;
    }

    public String getDocumentoFormal() {
        return documentoFormal;
    }

    public String getSubNameTeacher() {
        return subNameTeacher;
    }

    public void setSubNameTeacher(String subNameTeacher) {
        this.subNameTeacher = subNameTeacher;
    }

    public void setDocumentoFormal(String documentoFormal) {
        this.documentoFormal = documentoFormal;
    }

    public Date getDiaEmision() {
        return diaEmision;
    }

    public void setDiaEmision(Date diaEmision) {
        this.diaEmision = diaEmision;
    }

    public String getLugarSustentacion() {
        return lugarSustentacion;
    }

    public void setLugarSustentacion(String lugarSustentacion) {
        this.lugarSustentacion = lugarSustentacion;
    }

    public String getSecretario() {
        return secretario;
    }

    public void setSecretario(String secretario) {
        this.secretario = secretario;
    }

    public Integer getNotaFinal() {
        return notaFinal;
    }

    public boolean isArchivo() {
        return archivo;
    }

    public void setArchivo(boolean archivo) {
        this.archivo = archivo;
    }

    public ReportPractice getReportPracticeFinal() {
        return reportPracticeFinal;
    }

    public void setReportPracticeFinal(ReportPractice reportPracticeFinal) {
        this.reportPracticeFinal = reportPracticeFinal;
    }

    public void setNotaFinal(Integer notaFinal) {
        this.notaFinal = notaFinal;
    }

    public String getSubTwo() {
        return subTwo;
    }

    public void setSubTwo(String subTwo) {
        this.subTwo = subTwo;
    }

    public String getSubTree() {
        return subTree;
    }
    
    public void setSubTree(String subTree) {
        this.subTree = subTree;
    }

    public String getSubOne() {
        return subOne;
    }

    public void setSubOne(String subOne) {
        this.subOne = subOne;
    }

    public String getSubFour() {
        return subFour;
    }

    public void setSubFour(String subFour) {
        this.subFour = subFour;
    }

    public List<String> getCondicion() {
        if (condicion == null) {
            condicion = new ArrayList<String>();
            condicion.add(Clazz.STATE.Name.APROVADO);
            condicion.add(Clazz.STATE.Name.DESAPROVADO);
            condicion.add(Clazz.STATE.Name.DESAPROVADO_CON_CORRECION);
        }
        return condicion;
    }

    public void setCondicion(List<String> condicion) {
        this.condicion = condicion;
    }

    public String getVocal1() {
        return vocal1;
    }

    public void setVocal1(String vocal1) {
        this.vocal1 = vocal1;
    }

    public String getVocal2() {
        return vocal2;
    }

    public void setVocal2(String vocal2) {
        this.vocal2 = vocal2;
    }

    public void setAdviserPractice(AdviserPractice adviserPractice) {
        this.adviserPractice = adviserPractice;
    }

    public void setSustentationPracticeService(ISustentationPracticeService sustentationPracticeService) {
        this.sustentationPracticeService = sustentationPracticeService;
    }

    public ReportPractice getReportPractice() {
        return reportPractice;
    }

    public void setReportPractice(ReportPractice reportPractice) {
        this.reportPractice = reportPractice;
    }

    public boolean isGlobalUpdateRegister() {
        return globalUpdateRegister;
    }

    public void setGlobalUpdateRegister(boolean globalUpdateRegister) {
        this.globalUpdateRegister = globalUpdateRegister;
    }

    public void setAdviserPracticeService(IAdviserPracticeService adviserPracticeService) {
        this.adviserPracticeService = adviserPracticeService;
    }

    public void setPracticeService(IPracticeService practiceService) {
        this.practiceService = practiceService;
    }

    public String getStateSelected() {
        return stateSelected;
    }

    public void setStateSelected(String stateSelected) {
        this.stateSelected = stateSelected;
    }

    public String getNombreDecano() {
//        System.out.println(this.getClass().getResource(PATH_DEFAULT._DOYEN).toString());
//        MFile file = new MFile(this.getClass().getResource(PATH_DEFAULT._DOYEN).toString());
//        System.out.println(file.getPath());
//        System.out.println(file.getReaderObject().size());
//        Vector vector = file.getReaderObject();
//        if( vector.isEmpty() ) {
//            file.setWriteObject("MSC. WALTER BERNUY BLANCO");
//        } else {
//            nombreDecano = (String)vector.get(0);
//        }
        
        return nombreDecano;
    }

    public String getAnuladoPoSupervisionDetalle() {
        return anuladoPoSupervisionDetalle;
    }

    public void setAnuladoPoSupervisionDetalle(String anuladoPoSupervisionDetalle) {
        this.anuladoPoSupervisionDetalle = anuladoPoSupervisionDetalle;
    }

    public boolean isSegundaCalificacion() {
        return segundaCalificacion;
    }

    public void setNombreDecano(String nombreDecano) {
        this.nombreDecano = nombreDecano;
    }
//</editor-fold>
}
